const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const date = new Date()
// 创建集合云函数入口函数
exports.main = async (event, context) => {
  try {
    var stage = event.stage
    //var studyLogs = await db.collection('studyLogs')
    //var students = await db.collection('student')
    const students = await db.collection('student')
    const studyLogs = await db.collection('studyLogs')
    switch (stage) {
      case '总榜': {
        var student = await students.where({ class: 5 }).orderBy('score', 'desc').get()
        student = student.data
        student.forEach(item => {
          item.level = getLevel(item.score)
        });
      } break
      case '月榜': {
        var student = await students.where({ class: 5 }).get()
        let firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
        let lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 1);
        console.log(firstDay)
        console.log(lastDay)
        student = student.data
        console.log(student)
        for (const item of student) {
          item.level = getLevel(item.score)
          var logs = await studyLogs.where({ student_id: item._id, create_time: _.and(_.gte(firstDay.getTime()), _.lt(lastDay.getTime())) }).field({ score: true }).get()
          logs = logs.data
          console.log(logs)
          if (logs) {
            item.score = 0
            for (const log of logs) {
              item.score += log.score
            }
          } else {
            item.score = 0
          }

        }
        //console.log(student)
        student.sort(compare('score'))
      } break
      case '周榜': {
        var student = await students.where({ class: 5 }).get()
        //console.log(date.getDate())
        //console.log(date.getDay())
        let firstDay = new Date(date.getFullYear(), date.getMonth(), date.getDate() - ((date.getDay() == 0) ? 7 : (date.getDay())))
        const lastDay = new Date(date.getFullYear(), date.getMonth(), date.getDate() - ((date.getDay() == 0) ? 7 : (date.getDay())) + 8);
        console.log(firstDay.getTime())
        console.log(lastDay.getTime())

        student = student.data
        console.log(student)
        for (const item of student) {
          item.level = getLevel(item.score)
          var logs = await studyLogs.where({ student_id: item._id, create_time: _.and(_.gte(firstDay.getTime()), _.lt(lastDay.getTime())) }).field({ score: true }).get()
          logs = logs.data
          console.log(logs)
          if (logs) {
            item.score = 0
            for (const log of logs) {
              item.score += log.score
            }
          } else {
            item.score = 0
          }

        }
        //console.log(student)
        student.sort(compare('score'))
      } break
      case '日榜': {
        var student = await students.where({ class: 5 }).get()
        let firstDay = new Date(date.toDateString())
        //const lastDay = new Date(date.toDateString()+1);
        //console.log(firstDay.getTime())
        //console.log(lastDay.getTime())

        student = student.data
        for (const item of student) {
          item.level = getLevel(item.score)
          var logs = await studyLogs.where({ student_id: item._id, create_time: _.and(_.gte(firstDay.getTime()), _.lt(firstDay.getTime() + 24 * 3600 * 1000)) }).field({ score: true }).get()
          logs = logs.data
          console.log(logs)
          if (logs) {
            item.score = 0
            for (const log of logs) {
              item.score += log.score
            }
          } else {
            item.score = 0
          }
        }
        //console.log(student)
        student.sort(compare('score'))
      } break
      default: {
        return { success: false, data: '选择有问题，需要检查程序。' }
      }
    }
    return {
      success: true,
      data: student
    }

  } catch (e) {
    // 这里catch到的是该collection已经存在，从业务逻辑上来说是运行成功的，所以catch返回success给前端，避免工具在前端抛出异常
    return {
      success: false,
      data: e
    }
  }
}
function compare(prop, sort = 'desc') {
  return function (obj1, obj2) {
    var i = 'desc' == sort ? (-1) : 1
    var val1 = obj1[prop];
    var val2 = obj2[prop];
    if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
      val1 = Number(val1);
      val2 = Number(val2);
    }
    if (val1 < val2) {
      return (-1) * i;
    } else if (val1 > val2) {
      return 1 * i;
    } else {
      return 0;
    }
  }
}
function getLevel(score) {
  var level = ''
  if (score <= 100) {
    level = '初学乍练'
  } else if (score <= 110) {
    level = '略有小成'
  } else if (score <= 130) {
    level = '渐入佳境'
  } else if (score <= 160) {
    level = '炉火纯青'
  } else if (score <= 190) {
    level = '已臻大成'
  } else if (score <= 230) {
    level = '登峰造极'
  } else if (score <= 280) {
    level = '出神入化'
  } else if (280 < score) {
    level = '神通绝世'
  }
  return level
}